package de.ready4fajir.anywear.persistence;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ProfileOpenHelper extends SQLiteOpenHelper {

	private static final int DATABASE_VERSION = 1;
    private static final String DATABASE_NAME = "anywear";
    private static final String TABLE_NAME = "profiles";
    private static final String ROW_ID = "_id";
    private static final String PROFILE_NAME = "name";
    private static final String PROFILE_ACTIVE = "active";
    /**
     * Foreign key, pointing to the phone settings table, which stores the
     * settings made by the user, in relation to the profile ID.
     */
    private static final String PROFILE_SETTINGS_ID = "phoneSettingFk";

    public static final String [] FROM = {PROFILE_NAME, ROW_ID, PROFILE_ACTIVE};
    private static final String ORDER_BY = PROFILE_NAME + " DESC";
    
    private static final String DICTIONARY_TABLE_CREATE =
                "CREATE TABLE " + TABLE_NAME + " (" +
                ROW_ID +  " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                PROFILE_NAME + " TEXT, " +
                PROFILE_ACTIVE + " TEXT, " +
                PROFILE_SETTINGS_ID + " INTEGER);";
    	
	public ProfileOpenHelper(Context context)
	{
        super(context, DATABASE_NAME, null, DATABASE_VERSION);		
	}
	
	@Override
	public void onCreate(SQLiteDatabase database) {
		database.execSQL(DICTIONARY_TABLE_CREATE);
	}
	
	/**
	 * Adds a new profile to the database.
	 */
	public void addProfile(String profileName, boolean active)
	{
		SQLiteDatabase database = this.getReadableDatabase();
		ContentValues values = new ContentValues();
		values.put(PROFILE_NAME, profileName);
		values.put(PROFILE_ACTIVE, active);
		database.insertOrThrow(TABLE_NAME, null, values);
		
		//TODO profile settings must be saved in another table
	}

	/**
	 * Returns a list of all available profiles.
	 */
	public Cursor getProfiles()
	{
		SQLiteDatabase database = this.getReadableDatabase();
		Cursor cursor = database.query(TABLE_NAME, FROM, null, null, null, null, ORDER_BY);	
		Log.d("getProfiles()", "Number of profiles in the database: " + cursor.getCount());
		return cursor;
	}

	/**
	 * Deletes a the profile with a given ID.
	 */
	public void removeProfile(int iD)
	{
		//TODO
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		//TODO left to be down in case of a db upgrade
	}

	/**
	 * Deletes all profile entries.
	 */
	public void dropAll() {
		SQLiteDatabase database = this.getReadableDatabase();
		database.execSQL("delete from " + TABLE_NAME);
	}

}
